package web

import (
	"blive/tools"
	"fmt"
	"io"
	"log"
	"net/http"
)

//var pathlist []string

func Init(port string) {
	var conf = tools.Conf

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		src := `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>推流Web管理页面</title></head><body><div><button onclick="add">添加到播放列表</button><form name="form"action="/"method="post">请输入推流的文件/文件夹<input id="path"style="width: 100%;"type="text"name="path"><p>请输入推流的密钥<input style="width: 100%;"type="text"name="pwd"/></p><button type="submit"style="width: 100%;background-color: aquamarine;">推流</button></form>正在推流的<ul id="myid"><li>视频列表</li></ul></div></body><script>var host=window.location.host;var httpRequest=new XMLHttpRequest();function add(){var p=document.getElementById("path").value;httpRequest.open('POST',"http://"+host+'/plist',true);httpRequest.send("addpath="+p)}httpRequest.open('GET',"http://"+host+'/plist',true);httpRequest.send();httpRequest.onreadystatechange=function(){if(httpRequest.readyState==4&&httpRequest.status==200){var json=httpRequest.responseText;var List=json.split(",");List.forEach(element=>{var ele=document.createElement('li');ele.textContent=element;document.getElementById('myid').appendChild(ele)})}};</script></html>`
		io.WriteString(w, src)
		if r.Method == "POST" {
			path := r.PostFormValue("path")
			key := r.PostFormValue("pwd")
			conf.StreamKey = key
			// 为了不阻塞 web界面
			go player(path)
		}
	})
	helloHandler := func(w http.ResponseWriter, req *http.Request) {
		fmt.Println("获取了播放列表")
		if req.Method == "POST" {
			fmt.Println("添加到播放列表")
		}
		io.WriteString(w, conf.FilePath)
	}
	http.HandleFunc("/plist", helloHandler)
	fmt.Printf("服务启动在 http://localhost:%s\n", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}
